package com.mm.fam.web.controller;

import com.mm.fam.auth.security.TokenManager;
import com.mm.fam.common.utils.LoggerUtils;
import com.mm.fam.web.base.ResponseEntitySelf;
import com.mm.fam.web.entity.SysMenu;
import com.mm.fam.web.entity.SysPermission;
import com.mm.fam.web.entity.SysRole;
import com.mm.fam.web.entity.SysUser;
import com.mm.fam.web.entity.ins.AuthMenuTreeIns;
import com.mm.fam.web.entity.ins.SysUserInfo;
import com.mm.fam.web.service.SysMenuService;
import com.mm.fam.web.service.SysPermissionService;
import com.mm.fam.web.service.SysRoleService;
import com.mm.fam.web.service.SysUserService;
import com.mm.fam.web.vo.MenuOperateAccredit;
import com.mm.fam.web.vo.UserRole;
import com.mm.fam.web.vo.UserToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.DisabledAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录
 */
@Api(value="登陆模块")
@RestController
@RequestMapping("/api/user")
public class LoginController {
    Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private SysPermissionService sysPermissionService;
	@Autowired
	private SysRoleService sysRoleService;


	@ApiOperation(value="用户注册", notes="用户注册")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="body", required=false, name = "user", value = "用户对象", dataType = "SysUser"),
		@ApiImplicitParam(paramType="query", required=false, name = "rememberMe", value = "记住我", dataType = "boolean"),
		@ApiImplicitParam(paramType="query", required=false, name = "captcha", value = "验证码", dataType = "string")
	})
	@PostMapping(value = "/login")
	public ResponseEntitySelf<SysUserInfo> doLogin(@RequestBody SysUser user, Boolean rememberMe, String captcha, HttpServletRequest request, RedirectAttributes redirect) {
		ResponseEntitySelf<SysUserInfo> res = new ResponseEntitySelf<SysUserInfo>();
		try {
			TokenManager.login(user, rememberMe);
			UserToken token = TokenManager.getToken();
			SysUserInfo su = new SysUserInfo(token);

			// TODO Set Token·
			try {
				sysUserService.updateLoginTime(token.getId());
			} catch (Exception e) {
				LoggerUtils.error(getClass(), "更新系统用户登录时间失败:" + e.getMessage());
			}
			res.setData(su).success("登录成功");

			// 沈阳演示环境   登录提示
//			kafkaSimpleProducer.sendKafkaMsg("LoginMsg","{\"msg\":{\"time\":\""+ DateUtils.formatDateToString("yyyy-MM-dd HH:mm:ss")+"\",\"user\":\"ZhangXuDong\",\"account\":\""+user.getUsername()+"\"},\"type\":\"loginmsg\",\"title\":\"账户登录提示\"}");
		} catch (DisabledAccountException e) {
			res.failure("账号被禁用");
		} catch (Exception e) {
			e.printStackTrace();
			res.failure("用户名或密码错误");
		}
		return res;
	}


	@ApiOperation(value="获取用户信息", notes="获取用户信息")
	@GetMapping(value = "/getInfo")
	public ResponseEntitySelf<Map<String, Object>> getInfo() {
		ResponseEntitySelf<Map<String, Object>> res = new ResponseEntitySelf<Map<String, Object>>();
		// 构造权限返回值
		Map<String, Object> loginInofMap = new HashMap<String, Object>(16);

		Integer userId = null;

		try {
			userId = TokenManager.getUserId();
			if(userId == null) {
				// 重新登录
				res.failure("获取用户信息失败");
			} else {
				// 获取用户信息
				String nickname = TokenManager.getNickname();
				String avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";

                List<SysRole> roleList = sysRoleService.getRoleByUserId(userId);

                //获取用户机构信息
//				List<Integer> organizationIds = sysMenuService.queryOrganizationByUserId(userId);

				//获取当前用户拥有得操作权限
				List<MenuOperateAccredit> permissionList = sysPermissionService.getRoleEnableOperateAccreditList(roleList.get(0).getId());

				for(SysRole sysRole : roleList){
                    sysRole.setPermissions(permissionList);
                }
                loginInofMap.put("userId", userId);
                loginInofMap.put("avatar", avatar);
                loginInofMap.put("name", nickname);
                loginInofMap.put("roles", roleList);
//				loginInofMap.put("organizationIds", organizationIds);

				res.setData(loginInofMap);
				res.success("获取用户信息成功");
			}

		}catch (Exception e){
			e.printStackTrace();

		}
		return res;
	}

	@ApiOperation(value="退出登陆", notes="退出登陆")
	@GetMapping(value = "/logout")
	public ResponseEntitySelf<String> logout() {
		ResponseEntitySelf<String> res = new ResponseEntitySelf<String>();
		try {
			TokenManager.logout();
		}catch (Exception ignore){

		}
		res.success("登出成功");
		return res;
	}

	/**
	 * 处理菜单
	 * @param menus
	 * @return
	 */
	private List<Map<String, Object>> handleMenus(List<AuthMenuTreeIns> menus) {
		List<Map<String, Object>> tempMenus = new ArrayList<Map<String, Object>>();
		for(AuthMenuTreeIns a : menus) {
			Map<String, Object> tempMap = new HashMap<String, Object>(16);
			tempMap.put("name", a.getName());
			tempMap.put("path", a.getPath());
			if (a.getChildren().size() != 0) {
				tempMap.put("children", handleMenus(a.getChildren()));
			}
			tempMenus.add(tempMap);
		}
		return tempMenus;
	}

	/**
	 * 处理操作权限
	 * @param permissions
	 * @return
	 */
	private List<String> handlePermissions(List<SysPermission> permissions) {
		List<String> tempPermissionList = new ArrayList<String>();
		for(SysPermission s : permissions) {
			if (s.getAction().indexOf("#") > -1) {
				continue;
			}
			tempPermissionList.add(s.getAction());
		}
		return tempPermissionList;
	}

	/**
	 * 处理角色
	 * @param roles
	 * @return
	 */
	private List<Integer> handleRoles(List<UserRole> roles) {
		List<Integer> tempRoles = new ArrayList<Integer>();
		for(UserRole u : roles) {
			tempRoles.add(u.getId());
		}
		return tempRoles;
	}

	/**
	 * 处理角色菜单
	 * @param roles
	 * @return
	 */
	private List<String> handleRolesMenus(List<SysMenu> roles) {
		List<String> tempMenus = new ArrayList<String>();
		for(SysMenu s : roles) {
			tempMenus.add(s.getUrl());
		}
		return tempMenus;
	}

	/**
	 * 处理角色id
	 * @param roles
	 * @return
	 */
	private List<Integer> getRolesId(List<UserRole> roles) {
		List<Integer> tempRoles = new ArrayList<Integer>();
		for(UserRole u : roles) {
			tempRoles.add(u.getId());
		}
		return tempRoles;
	}

}
